import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DictionaryService {
  static Database? _db;
  static bool _initialized = false;

  /// 初始化数据库
  static Future<void> init({
    Function(double progress, String message)? progressCallback,
  }) async {
    if (_initialized) {
      progressCallback?.call(1.0, '词典已就绪');
      return;
    }

    try {
      progressCallback?.call(0.1, '正在准备数据库...');
      
      final dbPath = await getDatabasesPath();
      final path = join(dbPath, 'stardict.db');
      
      progressCallback?.call(0.2, '检查数据库文件...');
      bool exists = await databaseExists(path);

      if (!exists) {
        progressCallback?.call(0.3, '正在复制数据库文件...');
        try {
          await Directory(dirname(path)).create(recursive: true);
          ByteData data = await rootBundle.load('assets/db/stardict.db');
          List<int> bytes = data.buffer.asUint8List();
          await File(path).writeAsBytes(bytes, flush: true);
          progressCallback?.call(0.6, '数据库文件复制完成');
        } catch (e) {
          progressCallback?.call(0.0, '复制数据库失败: $e');
          return;
        }
      }

      progressCallback?.call(0.7, '正在打开数据库...');
      _db = await openDatabase(path, readOnly: true);
      
      /* 不验证数据了，太卡了
      progressCallback?.call(0.8, '正在验证数据...');
      final count = Sqflite.firstIntValue(
        await _db!.rawQuery('SELECT COUNT(*) FROM stardict')
      );
      */
      
      progressCallback?.call(0.9, '正在完成初始化...');
      _initialized = true;
      
      progressCallback?.call(1.0, '词典加载完成');
    } catch (e) {
      progressCallback?.call(0.0, '初始化失败: $e');
      rethrow;
    }
  }

  /// 查询单词
  static Future<Map<String, dynamic>?> queryWord(String word) async {
    if (_db == null) {
      print('数据库未初始化');
      return null;
    }

    try {
      final results = await _db!.query(
        'stardict',
        columns: ['word', 'phonetic', 'translation', 'definition', 'collins'],
        where: 'word = ?',
        whereArgs: [word.toLowerCase()],
        limit: 1,
      );

      if (results.isEmpty) return null;

      return {
        'word': results.first['word'] as String,
        'phonetic': results.first['phonetic'] as String? ?? '',
        'translation': results.first['translation'] as String? ?? '',
        'definition': results.first['definition'] as String? ?? '',
        'collins': results.first['collins'] as int? ?? 0,
      };
    } catch (e) {
      print('查询失败: $e');
      return null;
    }
  }

  /// 模糊查询
  static Future<List<Map<String, dynamic>>> searchWords(String keyword) async {
    if (_db == null) return [];

    try {
      return await _db!.query(
        'stardict',
        columns: ['word', 'translation'],
        where: 'word LIKE ?',
        whereArgs: ['$keyword%'],
        limit: 10,
      );
    } catch (e) {
      print('搜索失败: $e');
      return [];
    }
  }

  /// 获取词形变化
  static Future<String?> getWordExchange(String word) async {
    if (_db == null) return null;

    try {
      final results = await _db!.query(
        'stardict',
        columns: ['exchange'],
        where: 'word = ?',
        whereArgs: [word.toLowerCase()],
        limit: 1,
      );

      if (results.isEmpty) return null;
      return results.first['exchange'] as String?;
    } catch (e) {
      print('获取词形变化失败: $e');
      return null;
    }
  }

  /// 关闭数据库
  static Future<void> close() async {
    await _db?.close();
    _db = null;
    _initialized = false;
  }
} 